package com.sc.byahi.user.server;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.sc.byahi.user.shared.Profile;
import com.sc.byahi.user.shared.SharedUtil;
import com.sc.byahi.user.shared.constants.Config;

public class ImageUploader extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger("com.sc.byahi.user.server.ImageUploader");

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		logger.log(Level.WARNING, "Upload method called by user: " + user);
		if (StoreUtil.DEV_MODE || Config.bulkTestUpload) {
			String email = req.getParameter("email");
			user = new User(email, "byahi.com");
		}
		String profileId = req.getParameter("profileid");
		Long pId = SharedUtil.getLong(profileId);

		if (pId != null) {
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			try {
				Entity p = datastore.get(KeyFactory.createKey(Profile.class.getSimpleName(), pId));
				String owner = (String) p.getProperty(Profile.OWNER);
				if (owner.equals(user.getEmail()) || userService.isUserAdmin()) {
					List<BlobKey> uploadedBlobKeys = StoreUtil.getUploadedBlobs(req);
					logger.log(Level.WARNING, "Saving uploaded normal size images to profile." + uploadedBlobKeys);
					StoreUtil.replaceProfileImages(uploadedBlobKeys, datastore, p);

					// now create task here and schedule it
					Queue queue = QueueFactory.getDefaultQueue();
					queue.add(TaskOptions.Builder.withUrl("/admin/taskresize").param("profileid", profileId).method(Method.GET));
				}
			} catch (EntityNotFoundException e) {
				logger.log(Level.SEVERE, "Entity not found for id:" + pId);
				res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				// res.flushBuffer();
			}
		}
		res.setStatus(HttpServletResponse.SC_OK);
		// res.flushBuffer();
	}
}
